<?php 
namespace clt\monthly\driver;
use clt\monthly\driver;
use think\Cache;
use think\Exception;
class Megaport extends Driver{
	public $username = 'sheldon@cncarecc.com';//'gerry@cncarecc.com';
	public $password = 'b6192d';//'f4f0aa';
	public $dom = "https://api.megaport.com/";
	public $token = "";
    public $alocationId = 47;//香港出发
    public $productUid = '868308ab-b0ab-4e38-96c2-ba130b73f79e'; //香港点
	public function __construct($options=[])
    {
        
    }
	/**
     * 获取Token
     * @access public
     * @return bool
     */
    public function getToken()
    {
        $this->token = '';//Cache::get('megaport_token'); 
        if(empty($this->token)){
            $curl = new \clt\Curl;
            //gerry@cncarecc.com  f4f0aa
            $result = $curl->_post($this->dom.'v2/login',['username'=>$this->username,'password'=>$this->password]);
            $result = json_decode($result,true);
            $this->token = isset($result['data']['token']) ? $result['data']['token'] : false;
            Cache::set('megaport_token', $this->token,86400); 
        }

    	return $this->token;
		
    }
	/**
     * 获取地点
     * @access public
     * @return bool
     */
    public function getLocations()
    {
        $locations = '';// Cache::get('megaport_locations');
        if(empty($locations)){
            $curl = new \clt\Curl;
            $header = array("X-Auth-Token:".$this->token);
            $result = $curl->_get($this->dom.'v2/locations',$header);
            $results = json_decode($result,true);
            
            $data = [];
            if($results['data']){
                foreach($results['data'] as $vo){
                    $data[$vo['id']]['country'] = $vo['country'];
                    $data[$vo['id']]['city'] = isset($vo['address']['city']) ? $vo['address']['city'] : '';
                    $data[$vo['id']]['name'] = $vo['name'];
                    if(!empty($vo['address']['street'])){
                        db('pops')->where(['address'=>$vo['address']['street']])->update(['locationId'=>$vo['id']]);
                    }
                }
                
                $locations = $data;
                Cache::set('megaport_locations', $locations,0);
                
            }
        }
        return $locations;
    }
    /**
     * 获取通道
     * @access public
     * @return bool
     */
    public function getPorts(){
        $ports =  Cache::get('megaport_ports'); 
        $locations = $this->getLocations();
        if(empty($ports)){
            $curl = new \clt\Curl;
            $header = array("X-Auth-Token:".$this->token);
            $result = $curl->_get($this->dom.'v2/dropdowns/partner/megaports',$header);
            $data = json_decode($result,true);
            $base = [];
            $i=0;
            if($data['data']){
                foreach($data['data'] as $key=>$vo){
                    //$pid = db('areas')->where(['name'=>$locations[$vo['locationId']]['country'],'pid'=>0])->value('id');
                    //db('areas')->where(['name'=>$locations[$vo['locationId']]['city'],'pid'=>123])->update(['mageport_locationid'=>$vo['locationId']]);
                    $base[$vo['locationId']]['clouds'][$vo['connectType']] = $vo['connectType'];
                    $base[$vo['locationId']]['title']=$vo['title'];
                    $base[$vo['locationId']]['companyName']=$vo['companyName'];
                    $base[$vo['locationId']]['area'] = $locations[$vo['locationId']];
                    $data['data'][$key]['update_time'] = date('Y-m-d H:i:s',time());
                }
                $ports = $base;
                Cache::set('megaport_ports', $ports,86400*7); //一周过期
                /*存到数据库中*/
                db('megaports')->where('1=1')->delete();
                db('megaports')->insertAll($data['data']);
            }
        }
        return $ports;
    }
    /*购买云端 vlan = 609,608,610*/
    public function Buy($data){
        $header = array("X-Auth-Token:".$this->token,'Content-Type:application/json');
        $productUid = $this->productUid; //香港点
        $backProductUid = '';
        $config = db('network_config')->where(['network_id'=>$data['network_id']])->find();
        switch (intval($data['cloud_id'])) {
            case 3737: //ASW Cloud
                $item = db('cloud_items')->where(['id'=>$data['data_content']])->field('name,location_id')->find();
                if(empty($item) || intval($item['location_id']) <= 0){
                    throw new Exception("Error! Lack of resources", -404);
                }
                $map['connectType'] = 'AWS';
                $map['locationId'] = $item['location_id'];
                $map['vxcPermitted'] = 1;
                $productUids = db('megaports')->where($map)->value('productUid');
                if(empty($productUid)){
                    throw new Exception("Error! Lack of productUid", -404);
                }
                //$productUid =  '868308ab-b0ab-4e38-96c2-ba130b73f79e';
                $base['productUid'] = $productUid;
                $base['associatedVxcs'][] = array(
                    'productName' => $data['title'],
                    'rateLimit' => $data['rateLimit'],
                    'partnerConfigs' => array(
                        'connectType' => $map['connectType'],
                        'type' => 'private',
                        'asn' => $config['back_asn'],
                        'ownerAccount' => $data['account'],
                        'authKey' => $data['authKey'],
                        'prefixes' => $data['prefixes'],
                        'customerIpAddress' => $config['backboundary_ip'],
                        'amazonIpAddress' =>  $config['boundary_ip'],
                    ),
                    'aEnd' => array(
                        'vlan' => $config['vlan_cloud'],
                    ),
                    'bEnd' => array(
                        'productUid' => $productUids
                    ),
                );
                $backProductUid = $productUids;
                break;
            case 3789: //Alibaba
                 $item = db('cloud_items')->where(['id'=>$data['data_content']])->field('name,location_id')->find();
                if(empty($item) || intval($item['location_id']) <= 0){
                    throw new Exception("Error! Lack of resources", -404);
                }
                $map['connectType'] = 'ALIBABA';
                $map['locationId'] = $item['location_id'];
                $map['vxcPermitted'] = 1;
                $productUids = db('megaports')->where($map)->value('productUid');
                if(empty($productUid)){
                    throw new Exception("Error! Lack of productUid", -404);
                }
                $base['productUid'] = $productUid;
                $base['associatedVxcs'][] = array(
                    'rateLimit' => $data['rateLimit'],
                    'productName' => $data['title'],
                    'aEnd'=>array(
                          'vlan' => $config['vlan_cloud'],
                       ),
                    'bEnd'=>array(
                            'productUid' => $productUids,
                            'partnerConfig'=>array(
                                'vbrOwnerId' => $data['account'],
                                'connectType' => $map['connectType']
                            ),
                        )
                );
                $backProductUid = $productUids;
                # code...
                break;
            case 3738: //Azure
                $curl = new \clt\Curl;
                $result = $curl->_get($this->dom."v2/secure/Azure/{$data['authKey']}",$header);
                if($result == false || $result['message'] != 'Successful lookup'){
                    throw new Exception("Error! Lack of resources", -404);
                }
                $result = json_decode($result,true);
                $base['productUid'] = $productUid;
                $base['associatedVxcs'][] = array(
                        'rateLimit' => $data['rateLimit'],
                        'productName' => $data['title'],
                        'aEnd'=>array(
                              'vlan' => $config['vlan_cloud'],
                           ),
                        'bEnd'=>array(
                                'productUid' => $result['data']['megaports'][0]['productUid'],
                                'vlan' => $result['data']['vlan'],
                                'partnerConfig'=>array(
                                    'serviceKey' => $result['data']['service_key'],
                                    'connectType' => 'AZURE',
                                    'peers'=>array(
                                        array('type' => 'private'),
                                        array('type' => 'microsoft'),
                                    )
                                ),
                            ),
                        'productType' => 'VXC'
                    );
                $backProductUid = $result['data']['megaports'][0]['productUid'];
                # code...
                break; //7ad1e362-f578-46ea-a091-e7be26c1577f/asia-east1/1
            case 3739: //Google
                    $item = db('cloud_items')->where(['id'=>$data['data_content']])->field('name,location_id')->find();
                    if(empty($item) || intval($item['location_id']) <= 0){
                        throw new Exception("Error! Lack of resources", -404);
                     }
                     $map['connectType'] = 'GOOGLE';
                     $map['locationId'] = $item['location_id'];
                     $map['vxcPermitted'] = 1;
                     $productUids = db('megaports')->where($map)->value('productUid');
                     if(empty($productUids)){
                        throw new Exception("Error! Lack of productUid", -404);
                    }
                    $curl = new \clt\Curl;
                    //$this->dom."v2/secure/google/{$data['authKey']}";
                    $result = $curl->_get($this->dom."v2/secure/google/{$data['authKey']}",$header);
                    if(empty($result) || $result==false){
                        throw new Exception("Error! Lack of resources", -404);
                    }
                    $result = json_decode($result,true);
                    if(!isset($result['message']) || $result['message'] != 'Successful lookup'){
                        throw new Exception("Error! Lack of resources", -404);
                    }
                    $base['productUid'] = $productUid;
                    $base['associatedVxcs'][] = array(
                            'rateLimit' => $data['rateLimit'],
                            'productName' => $data['title'],
                            'productUid' => $productUids, //VXC 
                            'aEnd'=>array(
                                  'vlan' => $config['vlan_cloud'],
                               ),
                            'bEnd'=>array(
                                    'productUid' => $result['data']['megaports'][0]['productUid'],
                                    'partnerConfig'=>array(
                                        'pairingKey' => $data['authKey'],
                                        'connectType' => 'GOOGLE'
                                    ),
                                ),
                            'productType' => 'VXC'
                        );
                    $backProductUid = $productUids;
                   # code...
                   break;   
            default:
                # code...
                break;
        }
        
        //var_dump($header);
        //echo json_encode(array($base));
        //return false;
        $curl = new \clt\Curl;
        $result = $curl->_post($this->dom.'v2/networkdesign/buy',json_encode(array($base)),false,$header);
        if($result === false){
            throw new Exception("Error Processing Request", -404);
        }
        file_put_contents("open.log", $result."\n\n",FILE_APPEND);
        $result = json_decode($result,true);
        if(!$result['data'][0]['vxcOrderId']){
            if(isset($result['message']) && $result['message'] == 'Validation failed'){
                $error = array_values($result['data'][0]);
                if(isset($error[0])){
                    throw new Exception($error[0], -404);
                }
            }
            throw new Exception("Error! Failure to open ", -404);
        }
        return array('code'=>1,'productUid'=>$result['data'][0]['vxcJTechnicalServiceUid'],'msg'=>'success') ;
        // return isset($result['data'][0]['vxcOrderId']) ? array('code'=>1,'productUid'=>$backProductUid,'msg'=>'success') : array('code'=>0,'productUid'=>'','msg'=>$result['message']);
    }
    /*购买端口*/
    public function BuyPort($data){        
        $header = array("X-Auth-Token:".$this->token,'Content-Type:application/json');
        $row = db('pops')->where(['id'=>$data['pop_id']])->find();
        if(!empty($row['productUid'])){
            //return $row['productUid'];
        }
        $locationId = $row['locationId'];
        $data = array(
            'locationId' => 2,
            'term' => $data['term'] > 1 ? 12 : 1,
            'locationUid' => '',
            'productName' => $data['title'],
            'productType' => 'MEGAPORT',
            'createDate' => microtime(),
            'portSpeed' => 1000,
            'virtual' => false,
            'market' =>'',
        );
        $result =  $this->validate(array($data));
        $result = json_decode($result,1);
        if(!$result || $result['message'] == 'Validation failed'){
            if(isset($result['data']) && is_string($result['data'])){
                throw new Exception($result['data'], -404);
            }else if(is_array($result['data']) && isset($result['data'][0]['error'])){
                throw new Exception($result['data'][0]['error'], -404);
            }
            throw new Exception('request failure.', -404);
        }
        $curl = new \clt\Curl;
        unset($data['locationUid']);
        //$this->dom."v2/secure/google/{$data['authKey']}";
        $result = $curl->_post($this->dom."v2/networkdesign/buy",json_encode(array($data)),false,$header);
        $result = json_decode($result,1);
        if(empty($result) || $result==false || $result['message'] == 'Validation failed'){
            if($result['data'] && is_string($result['data'])){
                 throw new Exception($result['data'], -404);
            }else if(is_array($result['data']) && isset($result['data'][0]['error'])){
                throw new Exception($result['data'][0]['error'], -404);
            }
            throw new Exception('request failure.', -404);
        }
        // $base['network_id'] = $data['network_id'];
        // $base['service_uid'] = $result['data'][0]['technicalServiceId'];
        // $base['service_id'] = $result['data'][0]['technicalServiceUid'];
        // $base['type'] = $data['type'];
        // db('network_ports')->insert($base,true);
        db('pops')->where(['id'=>$data['pop_id']])->update(['productUid'=>$result['data'][0]['technicalServiceId']]);
        return $result['data'][0]['technicalServiceId'];
    }
    /*购买数据中心到数据中心*/
    public function BuyVXC($data){
         $base['productUid']  = $this->productUid;
         $productUid = $this->BuyPort($data);
         $config = db('network_config')->where(['network_id'=>$data['network_id']])->find();
         $base['associatedVxcs'][]  = array(
            'productName' => $data['title'],
            'rateLimit' => $data['rateLimit'],
            'aEnd' => array('vlan'=>$config['vlan_cloud']),
            'bEnd' => array('productUid'=>$productUid,'vlan'=>$config['vlan_cloud_inner']),
         );
         $header = array("X-Auth-Token:".$this->token,'Content-Type:application/json');
         $curl = new \clt\Curl;
         $resultd = $curl->_post($this->dom."v2/networkdesign/buy",json_encode(array($base)),false,$header);
         $resultd = json_decode($resultd,true);
         if(empty($resultd) || $resultd==false || $resultd['message'] == 'Validation failed'){
            if($resultd['data'] && is_string($resultd['data'])){
                 throw new Exception($resultd['data'], -404);
            }else if(is_array($result['data']) && isset($result['data'][0]['error'])){
                throw new Exception($result['data'][0]['error'], -404);
            }
            throw new Exception('request failure.', -404);
        }
        return array('code'=>1,'productUid'=>$resultd['data'][0]['vxcJTechnicalServiceUid'],'msg'=>'success') ;
    }
    /*产品*/
    public function product($productUid=null){
        $curl = new \clt\Curl;
        $header = array("X-Auth-Token:".$this->token,'Content-Type:application/json');
        $resultd = $curl->_get($this->dom."v2/products",$header);
        $result = json_decode($resultd,true);
        echo "<pre>";
        print_r($result);exit;
    }
    /**
     * 获取结果
     * @access public
     * @return bool
     */
    public function getUsage($condition){
        $header = array("X-Auth-Token:".$this->token,'Content-Type:application/json');
        $parameter = http_build_query($condition);
        $curl = new \clt\Curl;
        return $result = $curl->_get($this->dom."v2/graph/mbps?".$parameter,$header);
    }
    /**
     * 获取结果
     * @access public
     * @return bool
     */
    public function getPrice($blocationId,$sleep=10){
        $curl = new \clt\Curl;
        $header = array("X-Auth-Token:".$this->token);
        $result = $curl->_get($this->dom.'v2/pricebook/vxc?aLocationId='.$this->alocationId.'&speed='.$sleep.'&bLocationId='.$blocationId,$header);
        if($result === false){
            return false;
        }
        $result = json_decode($result,true);
        if(isset($result['data']['error']) || !isset($result['data']['monthlyRate'])){
            return false;
        }
        $rate = getRateOFHKD($result['data']['currency']); //汇率
        $monthlyRate = $result['data']['monthlyRate']*$rate;
        return isset($result['data']['monthlyRate']) ? $monthlyRate : 0;
    }

    /**
     * 新开通端口费用
     * @access public
     * @return bool
     */
    public function newPortPrice($locationId,$sleep=1000,$term=null){
        $curl = new \clt\Curl;
        $header = array("X-Auth-Token:".$this->token);
        $I = $term;
        $D=1;
        if(in_array($term,[3,6])){
            $I = 1;
            $D = $term;
        }
        $result = $curl->_get($this->dom.'v2/pricebook/megaport?speed='.$sleep.'&locationId='.$locationId."&term=".$I,$header);
        $result = json_decode($result,true);
        if(isset($result['data']['monthlyRate'])){
            $rate = getRateOFHKD($result['data']['currency']); //汇率
            $monthlyRate = $result['data']['monthlyRate']*$rate;
            return round($monthlyRate*$D) ;
        }
        return 0;
    }   
    /**
     * 获取结果
     * @access public
     * @return bool
     */
    public function getAllPrice($m){
        set_time_limit(0);

        $ports =  $this->getPorts(); 
        $data = [];
        $i=0;
        $locations = $this->getLocations();
        ksort($ports);
        $countrys = [];
        foreach($ports as $locationId => $port){
            $port['locationId'] = $locationId;
            $country = $locations[$locationId]['country'];
            $city = $locations[$locationId]['city'];
            if(isset($countrys[$country][$city]) || !isset($locations[$locationId]['country'])){
                continue;
            }
            $countrys[$country][$city] = $locationId;
            foreach($m as $mb){
                $port['items'][$mb]['type'] = '海外CCI';
                $port['items'][$mb]['mbps'] = $mb;
                $port['items'][$mb]['aLocations'] = 'Hong Kong';
                $port['items'][$mb]['country'] = $country;
                $port['items'][$mb]['city'] = $city;
                $total = $this->getPrice($locationId,$mb);
                $port['items'][$mb]['megaport_hkd'] = $total;
                $port['items'][$mb]['megaport_usd'] = round($total/6.5);
                $port['items'][$mb]['rmb12'] = round($total*1.5);
                $port['items'][$mb]['usd12'] = round(($total/6.5)*1.5);
                $port['items'][$mb]['rmb6'] = round($total*1.5*1.2);
                $port['items'][$mb]['usd6'] = round(($total/6.5)*1.5*1.2);
                $port['items'][$mb]['rmb3'] = round($total*1.5*1.2*1.3);
                $port['items'][$mb]['usd3'] = round(($total/6.5)*1.5*1.2*1.3);
                $port['items'][$mb]['rmb1'] = round($total*1.5*1.2*1.3*1.4);
                $port['items'][$mb]['usd1'] = round(($total/6.5)*1.5*1.2*1.3*1.4);
                $port['items'][$mb]['clouds'] = is_array($port['clouds']) ? implode(",", $port['clouds']):'';
                $port['items'][$mb]['locationId'] =  $locationId;
            }
            $data[] = $port;
            if($i>3){
               //break;
            }
            $i++;
        }
        $base['items'] = $data;
        $base['sheetnName'] =  "海外CCI";
        $base['headers'] = $headArr=['类型','宽带(Mbps)','A端','Z端地区','Z端城市','Megaport(元/月)','Megaport(美元/月)',"CNCARE(元/月)\n[年度]","CNCARE(美元/月)\n[年度]","CNCARE(元/月)\n[半年度]","CNCARE(美元/月)\n[半年度]","CNCARE(元/月)\n[季度]","CNCARE(美元/月)\n[季度]","CNCARE(元/月)\n[月度]","CNCARE(美元/月)\n[月度]",'云供应商',"locationId"];
        return $base;
    }
    /**
     * 验证数据
     * @access public
     * @return bool
     */
    private function validate($data){
        $this->header = array("X-Auth-Token:".$this->token,'Content-Type:application/json');
        $curl = new \clt\Curl;
        return $result = $curl->_post($this->dom.'v2/networkdesign/validate',json_encode($data),false,$this->header);
    }   
}
?>